import { Component, OnInit, Input } from '@angular/core';
import { TreeModule, TreeNode } from 'primeng/primeng';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { MdlSnackbarService } from '@angular-mdl/core';
import { ConfirmationService, SelectItem } from 'primeng/primeng';
import { FormDef } from '../fb-design.model';
import { FormDesignService } from '../fb-design.service';

@Component({
    selector: 'fb-baseinfo',
    templateUrl: './fb-baseinfo.component.html',
    styleUrls: ['./fb-baseinfo.component.scss'],
    providers: [ ]
})
export class FormBaseInfoComponent implements OnInit {
    
    baseInfoForm: FormGroup;
    formDef: FormDef = new FormDef({});
    formTree: TreeNode[];
    bizs: any[];

    @Input()
    set formId(formId: number){
        if (!formId) return;
        this.FormDesignService.showFormDefDetail(formId).subscribe(data =>{
            this.formDef = data;
            this.buildForm()
        })
    }

    get formId(): number { return this.formDef.formId; }

    constructor(
        private fb: FormBuilder,
        private FormDesignService: FormDesignService,
        private mdlSnackbarService: MdlSnackbarService,
        private confirmationService: ConfirmationService) {
    }

    ngOnInit() {
        this.buildForm();
    }
    /**保存或更新表单 */
    saveUpdate(){
        this.baseInfoForm.value['attachmentFlag'] = (this.baseInfoForm.value['attachmentFlag'] == true) ? 1 : 0;
        this.baseInfoForm.value['multiVersion'] = (this.baseInfoForm.value['multiVersion'] == true) ? 1 : 0;
        this.baseInfoForm.value['validFlag'] = (this.baseInfoForm.value['validFlag'] == true) ? 1 : 0;
        this.FormDesignService.saveUpdateFormDef(this.baseInfoForm.value)
        .subscribe(data => {
            this.FormDesignService.announceMission(data['formId'])
            this.mdlSnackbarService.showToast('表单信息保存成功！');
        });
    }
    /**移除表单 */
    delete() {
        this.confirmationService.confirm({
            header: '确认',
            message: '您确定要删除这个表单吗？',
            accept: () => {
                this.FormDesignService.deleteFormDef(this.formDef.formId).subscribe(data=>{
                    this.FormDesignService.announceMission(null);
                    this.mdlSnackbarService.showToast("删除表单《"+this.formDef.formName+"》操作成功");
                })
            }
        });
    }
    /** 推送表单到中央仓库 */
    push(){
        this.confirmationService.confirm({
            header: '确认',
            message: '您确定要将这个表单推送至表单仓库吗？',
            accept: () => {
                this.FormDesignService.pushRepo(this.formDef.formId).subscribe(data=>{
                    this.mdlSnackbarService.showToast("表单《"+this.formDef.formName+"》已成功添加到仓库！");
                })
            }
        });
    }

    buildForm(): void {
        this.baseInfoForm = this.fb.group({
            'formId': [this.formDef.formId, Validators.required],
            'formName': [this.formDef.formName, [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
            'bizId': [this.formDef.bizId],
            'bizName': [this.formDef.bizName, Validators.required],
            'procDefId': [this.formDef.procDefId],
            'procDefName': [this.formDef.procDefName, [Validators.minLength(50), Validators.required]],
            'displayOrder': [this.formDef.displayOrder],
            'attachmentFlag': [this.formDef.attachmentFlag],
            'multiVersion': [this.formDef.multiVersion],
            'groupName': [this.formDef.groupName],
            'createUser': [this.formDef.createUser],
            'createTime': [this.formDef.createTime],
            'formDesc': [this.formDef.formDesc]
        });

        this.baseInfoForm.valueChanges
            .subscribe(data => this.onValueChanged(data));

        this.onValueChanged();
    }

    onValueChanged(data?: any) {
        if (!this.baseInfoForm) { return; }
        const form = this.baseInfoForm;

        for (const field in this.formErrors) {
            this.formErrors[field] = '';
            const control = form.get(field);
            if (control && control.dirty && !control.valid) {
                const messages = this.validationMessages[field];
                for (const key in control.errors) {
                    this.formErrors[field] += messages[key] + ' ';
                }
            }
        }
    }

    formErrors = {
        'datasetName': '',
        'systemUrl': '',
        'datasetSql': ''
    };

    validationMessages = {
        'datasetName': {
            'required': '请输入数据源名称',
            'minlength': '数据源名称长度必须大于2',
            'maxlength': '数据源名称长度必须小于20'
        },
        'systemUrl': {
            'required': '请选择数据来源系统',
        },
        'datasetSql': {
            'required': '请输入获取数据SQL语句',
            'minlength': '获取数据SQL语句长度至少50个字符',
        }
    };
}
